from google.appengine.ext import db
from google.appengine.api import users
import datetime
import logging

#Entity data model
class EntitiesModel(db.Model):
    EntityAbbr	= db.StringProperty(required=True)
    EntityName 	= db.StringProperty(required=True)
    Address1	= db.StringProperty()
    Address2	= db.StringProperty()
    PostalCode	= db.StringProperty()
    City	= db.StringProperty()
    Phone	= db.StringProperty()
    Fax		= db.StringProperty()
    Email	= db.StringProperty()
    URL		= db.StringProperty()
    LatLng	= db.StringProperty()
    CreatedBy	= db.UserProperty(required=True)
    Responsible	= db.UserProperty(required=True)
    CreatedOn	= db.DateTimeProperty(auto_now_add=True)
    UpdatedOn	= db.DateTimeProperty(auto_now=True)
    UpdatedBy	= db.UserProperty()


def addEntity(vEntityAbbr, vEntityName, vAddress1, vAddress2, vPostalCode, vCity, vPhone, vFax, vEmail, vURL, vLatLng, vResponsible, user):
    """
    Add a new entity to the datastore.
  
    Returns  
	The id of the entity or None if the add failed.
    """
    logging.info('Start addEntity request')
    if user is None:
	return
  
    try:
	now = datetime.datetime.now()
	nEntity = EntitiesModel(
	    EntityAbbr	= vEntityAbbr,
	    EntityName 	= vEntityName,
	    Address1	= vAddress1,
	    Address2	= vAddress2,
	    PostalCode	= vPostalCode,
	    City	= vCity,
	    Phone	= vPhone,
	    Fax		= vFax,
	    Email	= vEmail,
	    URL		= vURL,
	    LatLng	= vLatLng,
	    CreatedBy	= user,
	    CreatedOn	= now,
	    Responsible	= vResponsible
	)
	nEntity.put()
	logging.info('End addEntity successfully')
	return nEntity.key().id()
    except db.Error:
	logging.error('Error: addEntity')
	return None



def updateEntity(EntityID, vEntityAbbr, vEntityName, vAddress1, vAddress2, vPostalCode, vCity, vPhone, vFax, vEmail, vURL, vLatLng, vResponsible, user):
    """
    Update an entity
    
    Returns the entity ID or None if an error occurred
    """
    logging.info('Start updateEntity')
    
    if user is None:
      return

    try:
	def transact():
	    now = datetime.datetime.now()
	    currEntity=EntitiesModel.get_by_id(int(EntityID))
	    currEntity.EntityAbbr	= vEntityAbbr
	    currEntity.EntityName 	= vEntityName
	    currEntity.Address1		= vAddress1
	    currEntity.Address2		= vAddress2
	    currEntity.PostalCode	= vPostalCode
	    currEntity.City		= vCity
	    currEntity.Phone		= vPhone
	    currEntity.Fax		= vFax
	    currEntity.Email		= vEmail
	    currEntity.URL		= vURL
	    currEntity.LatLng		= vLatLng
	    currEntity.Responsible	= vResponsible
	    currEntity.UpdatedBy	= user
	    currEntity.UpdatedOn	= now
	    currEntity.put()
	db.run_in_transaction(transact)
	
	logging.info('End updateEntity successfully')
	return EntityID
    except db.Error:
	logging.error('Error: upateEntity')
	return None
    


def deleteEntity(EntityID, user):
    """
    Delete an entity
    
    Returns  
      1 or 0 denpending on success
    """
    logging.info('Start deleteEntity ID=: %s' %EntityID)
    if user is None:
      return 0

    try:      
	def transact():
	    currEntity = EntitiesModel.get_by_id(int(EntityID))
	    currEntity.delete()
	db.run_in_transaction(transact)
	
	logging.info('End deleteEntity successfully ID=: %s' %EntityID)
	return 1
    except db.Error:
	logging.error('#Error deleteEntity ID= %s' %EntityID)
	return 0



def getEntities(user):
    """ 
    Returns  the entities list of the responsible user
    """
    if user is None:
      return None
    
    try:
	Entities = EntitiesModel.gql("")
  
	return Entities
    except db.Error:
	return None


def getEntity(EntityID, user):
    """ 
    Returns the entity with the ID = EntityID
    """
    if user is None:
      return  
    
    try:
	oEntity=EntitiesModel.get_by_id(int(EntityID))
	logging.info('End getEntity successfully: %s' % oEntity.EntityAbbr)
	return oEntity
    except db.Error:
	logging.error('#Error getEntity ID= %s' %EntityID)
	return None
    

def getID(EntityAbbr, user):
    """ 
    Returns the ID 
    """
    if user is None:
      return  
    
    try:
	oEntity=EntitiesModel.gql("WHERE EntityAbbr = :1", EntityAbbr).get()
	return oEntity.key().id()
    except db.Error:
	logging.error('#Error getID ID')
	return None

def getKey(EntityAbbr, user):
    """ 
    Returns the ID 
    """
    if user is None:
      return  
    
    try:
	oEntity=EntitiesModel.gql("WHERE EntityAbbr = :1", EntityAbbr).get()
	return oEntity.key()
    except db.Error:
	logging.error('#Error getKey Key')
	return None    